<template>
  <div>
    <el-container>
      <div style="display: flex ;margin-left: 10px;height: 10%;margin-top: 10px">
        <el-input v-model="input1" style="width: 240px" placeholder="请输入企业ID"/>
        <el-input v-model="input2" style="width: 240px" placeholder="请企业名" />
        <el-button :disabled="input1.length===0&&input2.length===0" @click='getEnterprise()'  type="primary">搜索</el-button>
        <el-button style="margin-left: 2vh" @click='clearInputs()'  type="info">全部企业</el-button>
      </div>
      <br>
      <el-table :data="enterprise" style="margin-left: -81.5vh;margin-top:10vh;width: 149vh;border-radius: 10px" >
        <el-table-column prop="id" label="企业ID" width="260"></el-table-column>
        <el-table-column prop="name" label="企业名" width="190"></el-table-column>
        <el-table-column prop="userNumber" label="企业人数" width="120"></el-table-column>
        <el-table-column prop="adminUserId" label="管理员ID" width="200"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="企业状态" width="100" >
          <template  #default="{row}">

              <div v-if="row.enterStatus==='FREEZE'">封禁</div>
              <div v-if="row.enterStatus==='NORMAL'">正常</div>

          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" >
          <template  #default="{row}">
            <el-button type="primary" :disabled="enterprise[0].id===''" @click="getEnterInfo(row)">查看详情</el-button>
          </template>
        </el-table-column>

      </el-table>

    </el-container>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="totals"
        v-if="isCanUser===false"
        v-model:page-size="pageSize"
        v-model:current-page= "pageCount"
        @change="getEnterprise()"
        class="mt-4"
        style="display: flex; justify-content: center;margin-top: 2vh"
    />
    <el-dialog
        v-model="inApproval"
        width="1000"
        :title="'企业管理:'+enterpriseInfo.name"
        :before-close="handleClose"
    >
      <div  style="text-align: center"><el-button size="large" style="margin-right: 30vh;width: 200px;height: 80px;font-size: 40px;background-color: #ace0f9" @click = "isUser=true">用户</el-button>
        <el-button size="large" @click = "getApproval(enterpriseInfo.id)" style="width: 200px;height: 80px;font-size: 40px;background-color: lemonchiffon">审批</el-button></div>
      <div v-if="isUser">
      <el-descriptions title="企业管理员信息" >
        <el-descriptions-item label="用户ID">{{sysUser.id}}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{sysUser.username}}</el-descriptions-item>
        <el-descriptions-item label="真实名">{{sysUser.realName}}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{sysUser.phone}}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{sysUser.email}}</el-descriptions-item>
        <el-descriptions-item label="用户状态">
            <div v-if="sysUser.userStatus==='FREEZE'">封禁</div>
            <div v-if="sysUser.userStatus==='CANDIDATE'">候选</div>
            <div v-if="sysUser.userStatus==='NORMAL'">正常</div>
        </el-descriptions-item>
        <el-descriptions-item label="修改企业管理员状态">
          <el-select  v-model="sysUser.type" placeholder="选择状态" style="width: 150px;" >
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
            />
          </el-select>
          <el-button @click="tokeUser(sysUser)">提交</el-button>
        </el-descriptions-item>
      </el-descriptions>
      <strong style="font-size: 15px">企业用户：</strong>
      <el-table :data="users" style="width: 119vh;border-radius: 5px" >
        <el-table-column prop="id" label="编号" width="130"></el-table-column>
        <el-table-column prop="username" label="用户名" width="80"></el-table-column>
        <el-table-column prop="realName" label="真实名" width="80"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="110"></el-table-column>
        <el-table-column prop="job" label="职务" width="110"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="150"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="用户状态" width="100" >

          <template  #default="{row}">
            <div v-if="users[0].id!==''">
              <div v-if="row.userStatus==='FREEZE'">封禁</div>
              <div v-if="row.userStatus==='CANDIDATE'">候选</div>
              <div v-if="row.userStatus==='NORMAL'">正常</div>
            </div>

        </template>
        </el-table-column>
        <el-table-column label="操作" width="100" >
          <template  #default="{row}">
            <el-button v-if="row.userType==='ENTERPRISE_ADMIN'" type="primary" :disabled="users[0].id===''" @click="tokeUser(row)">提交</el-button>
           <div v-if="row.userType!=='ENTERPRISE_ADMIN'">无</div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="prev, pager, next"
          :total="totals2"
          v-model:page-size="pageSize2"
          v-model:current-page= "pageCount1"
          @change="getUser(sysUser.enterpriseId)"
          class="mt-4"
          style="display: flex; justify-content: center;margin-top: 2vh"
      /></div>
      <div v-if="isUser===false">
        <el-input v-model="inputName" style="width: 30vh;margin-left: 2vh;float: left;margin-top: 2vh;" placeholder="输入审批名"/>
        <el-button plain @click="this.getApproval(pageCount)" style="width: 10vh;float: left;margin-top: 2vh;margin-left: 2vh">查询审批项</el-button>
        <el-table :data="statuA" style="margin-left: 1vh;width: 120vh;border-radius: 10px;text-align: left" >
          <el-table-column prop="id" label="审批项编号" width="220"></el-table-column>
          <el-table-column prop="processName" label="审批项名" width="120"></el-table-column>
          <el-table-column label="详情" width="120" >
            <template  #default="{row}">
            <el-button type="primary" @click="toApproval(row)">查看详情</el-button>
            </template>
          </el-table-column>
          <el-table-column prop= "createTime" label="创建时间" width="170"></el-table-column>
          <el-table-column label="审批项状态" width="220" >
            <template  #default="{row}">
              <div v-if="row.id!==''">
                <div v-if="row.status==='FREEZE'">暂停</div>
                <div v-if="row.status==='NORMAL'">正常</div>
              </div>

              <el-select v-model="row.type" placeholder="选择状态" style="width: 150px;float: right;margin-top: -23px" >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                />
              </el-select>   </template>
          </el-table-column>
          <el-table-column label="操作" width="100" >
            <template  #default="{row}"><el-button type="primary" :disabled="row.type===undefined" @click="updateStatus(enterpriseInfo.id,row.id,row.type)">提交</el-button> </template>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="totals3"
            v-model:page-size="pageSize2"
            v-model:current-page= "pageCount2"
            @change="getApproval(enterpriseInfo.id)"
            class="mt-4"
            style="display: flex; justify-content: center;margin-top: 2vh"
        />
      </div>
      <el-dialog  width="600"  v-model="isApproval">
      <el-descriptions
          title="审批流程详情"
          border
          :column="2"
          direction="vertical"
      >
        <!-- 基础信息 -->
        <el-descriptions-item label="流程名称">{{ approvals.processName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(approvals.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="创建人ID">{{ approvals.creatorId }}</el-descriptions-item>
        <el-descriptions-item label="企业ID">{{ approvals.enterpriseId }}</el-descriptions-item>
        <!-- 审批类型 -->
        <el-descriptions-item label="审批类型">
          {{ getOptionLabel(options3, approvals.configData.approvalItem.type) }}
        </el-descriptions-item>
        <!-- 控件类型 -->
        <el-descriptions-item label="控件类型" :span="2">
          {{ formatControls(approvals.configData.approvalItem.controls) }}
        </el-descriptions-item>
        <!-- 审批步骤 -->
        <el-descriptions-item
            v-for="(step, index) in approvals.configData.approvalSteps"
            :key="step.stepId"
            :label="`审批步骤 ${index + 1}`"
            :span="2"
        >
          <div class="step-container">
            <div><strong>步骤名称：</strong>{{ step.stepName}}</div>
            <div><strong>审批要求：</strong>{{ step.requirement  }}</div>
            <div><strong>审批人ID：</strong>{{ step.approvePeople }}</div>
            <div><strong>顺序：</strong>{{ step.order }}</div>
            <div><strong>要求：</strong>{{ step.requirement }}</div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      </el-dialog>

    </el-dialog>
  </div>

</template>

<script setup>

import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {now} from "@vueuse/core";
import {
  getCanNums,
  getSysUserInfo,
  updateInfoByIdService,
  userGetCanUser,
  userGetUser,
  userUpdateName
} from "@/api/user.js";
import useUserInfoStore from "@/stores/userInfo.js";
import {getEnterprises, getInfo} from "@/api/enterprise.js";
import {getApprovals, updateStatusById} from "@/api/Approval.js";
const type = ref()
const userInfo = useUserInfoStore()

const options = [
  {
    value: "normal",
    label: '正常/激活',
  },
  {
    value: "freeze",
    label: '封禁',
  },
]


const enterprise = ref([])
const isCanUser = ref(false)
const inputName = ref('')
const input1=ref('')
const input2=ref('')
const totals=ref(1)
const totals2=ref(1)
const totals3=ref(1)
const pageSize=ref(4)
const pageSize2=ref(3)
const pageCount=ref(Math.ceil(totals.value/pageSize.value))
const pageCount1=ref(Math.ceil(totals2.value/pageSize2.value))
const pageCount2=ref(Math.ceil(totals3.value/pageSize2.value))
const statuA = ref([])
const options3 = [{value: 1, label: '财务'},{value: 2, label: '人事'},{value: 3, label: '行政'}]
const options4 =  [{value: 'text', label: '文本输入'},{value: 'daterange', label: '时间'},{value: 'file', label: '文件'},{value: 'number', label: '数字'}]
const isApproval = ref(false)
const clearInputs=()=>{
  input1.value=''
  input2.value=''
  pageCount.value=1
  getEnterprise()
}
const isUser = ref(true)
const inApproval = ref(false)
//编辑用户状态
const tokeUser=(row)=>{
  ElMessageBox.confirm(
      '请问您确定要提交吗',
      '提醒',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        if (row.type===undefined){
          row.type='normal'
        }
        await updateInfoByIdService(row.id,row.job,row.type)
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        await getSysUser(row.enterpriseId)
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
      })

}
const getEnterprise = async () => {
  let res
  try {
    res  = await getEnterprises(input1.value,input2.value,pageCount.value,pageSize.value)
    isCanUser.value=false
    enterprise.value = res.list
    totals.value = res.total
  }catch(error) {
    ElMessage.error(error.response?.data?.msg || '查找失败')
  }
}
getEnterprise()
const enterpriseInfo = ref({name:null})
const getEnterInfo=async (row)=>{
  // let result = await getInfo(row.id)
  // enterpriseInfo.value = result.data
  enterpriseInfo.value=row
  inApproval.value = true
  await getSysUser(row.id)
  await getUser(row.id)
}
const sysUser = ref({
  username: null,
  email: null,
  phone: null,
  userStatus: null,
  realName: null,
  id: null,
  enterpriseId: null,
})
const getSysUser = async (id) => {
  let res
  try {
    res  = await getSysUserInfo(id)
    sysUser.value = res
  }catch(error) {
    ElMessage.error(error.response?.data?.msg || '查找失败')
  }
}
const users = ref()
const getUser = async (id) => {
  let res
  try {
    res  = await userGetUser(id,null,null,pageCount1.value,pageSize2.value)
    users.value = res.list
    totals2.value = res.total
    console.log(res)
  }catch(error) {
    ElMessage.error(error.response?.data?.msg || '查找失败')
  }
}
const updateStatus=async (eID,id,statu) =>{
  let res = await updateStatusById(id,statu)
  ElMessage.success(res)
  await getApproval(eID)
}
const getApproval=async (enterpriseId) => {
  isUser.value=false
  let res = await getApprovals(inputName.value, enterpriseId, pageCount2.value, pageSize2.value)
  totals3.value = res.total
  statuA.value = res.list
  if (statuA.value !== undefined) {
    for (let i = 0; i < statuA.value.length; i++) {
      statuA.value[i].configData = JSON.parse(statuA.value[i].configData)
    }
  }
}
const approvals = ref()
const toApproval=(row) =>{
  isApproval.value=true
  approvals.value=row
}
// 工具方法
const getOptionLabel = (options, value) => {
  const item = options.find(opt => opt.value === value)
  return item ? item.label : '未知'
}

const formatControls = (controls) => {
  return controls.map(c =>
      options4.find(opt => opt.value === c)?.label || c
  ).join(', ')
}

const formatDate = (isoString) => {
  return new Date(isoString).toLocaleString()
}
</script>

<style scoped lang="scss">

</style>